package com.ee.chat.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IImService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.UserImLogMapper;
import com.ee.chat.common.entity.UserImLog;
import com.ee.chat.common.serconfig.MyNeteaseApp;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.PageUtil;
import com.ndhutu.ee.util.StringUtil;
import com.ndhutu.ee.util.netease.im.IMUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author AppiJ
 * @Date 2020/4/24 11:55
 */
@Service
public class ImServiceImpl implements IImService {

    @Resource
    UserImLogMapper imLogMapper;
    @Resource
    IOperationService operationService;
    @Resource
    MyNeteaseApp app;

    @Override
    public Result list(HttpServletRequest request, Integer fromUserId, Integer toUserId,
                       String type, String time, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(time) && StringUtil.isEmpty(type) && fromUserId == null && toUserId == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/operate/im/viewList")){
                data.put("imLogs", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        List<Map<String, Object>> imLogs = imLogMapper.list(fromUserId, toUserId, type, beginTime, endTime, PageUtil.getOffset(page, limit), limit);
        for (Map<String, Object> imLog : imLogs) {
            if("CUSTOM".equals(imLog.get("type"))){
                Map<String, Object> attachMap = JSONObject.parseObject(imLog.get("attach")+"", Map.class);
                int attachType = Integer.parseInt(attachMap.get("type")+"");
                if(attachType == 743){
                    Map<String, Object> map = JSONObject.parseObject(attachMap.get("data").toString(), Map.class);

                    attachMap.put("data", map);
                    imLog.put("attach", attachMap);
                    imLog.put("msg", map.get("giftImg").toString());
                }
            }else if("AUDIO".equals(imLog.get("type"))){
                Map<String, Object> attachMap = JSONObject.parseObject(imLog.get("attach")+"", Map.class);
                imLog.put("msg", attachMap.get("url").toString());
            }
        }

        data.put("imLogs", imLogs);
        data.put("total", imLogMapper.listCount(fromUserId, toUserId, type, beginTime, endTime));

        operationService.addOperationLog(request, "获取消息列表数据");

        return Result.returnSuccess(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateStatus(HttpServletRequest request, List<Integer> ids) throws Exception {

        for(Integer id : ids){
            UserImLog imLog = imLogMapper.selectById(id);

            if(imLog.getStatus() == 1){
                continue;
            }

            imLog.setStatus(1);
            imLogMapper.updateById(imLog);

            //消息撤回
            IMUtil.recall(imLog.getMsgId(), Long.parseLong(imLog.getMsgTimestamp()), app.getIdPrefix()+imLog.getFromUserId(),
                    app.getIdPrefix()+imLog.getToUserId(), app);
        }

        operationService.addOperationLog(request, "变更消息处理状态，id："+ids);

        return Result.returnSuccess(null);
    }

    @Override
    public Result view(HttpServletRequest request, Integer kill, String time, Integer fromUserId,
                       Integer toUserId, String type, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = imLogMapper.queryBetweenUserMsg(p, fromUserId, toUserId, type, kill, beginTime, endTime);
        List<Map<String, Object>> imLogs = iPage.getRecords();
        if(imLogs != null && imLogs.size() != 0) {
            for (Map<String, Object> imLog : imLogs) {
                if("CUSTOM".equals(imLog.get("type"))){
                    Map<String, Object> attachMap = JSONObject.parseObject(imLog.get("attach").toString(), Map.class);
                    int attachType = Integer.parseInt(attachMap.get("type")+"");
                    if(attachType == 743){
                        Map<String, Object> map = JSONObject.parseObject(attachMap.get("data").toString(), Map.class);

                        attachMap.put("data", map);
                        imLog.put("attach", attachMap);
                        imLog.put("msg", map.get("giftImg").toString());
                    }
                }else if("AUDIO".equals(imLog.get("type"))){
                    Map<String, Object> attachMap = JSONObject.parseObject(imLog.get("attach").toString(), Map.class);
                    imLog.put("msg", attachMap.get("url").toString());
                }
            }
        }

        data.put("datas", imLogs);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查看聊天记录列表数据");

        return Result.returnSuccess(data);
    }

    @Override
    public Result kill(HttpServletRequest request, String date, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        String beginDate = null, endDate = null;
        if(!StringUtil.isEmpty(date)){
            String[] arr = date.split(" - ");
            beginDate = arr[0];
            endDate = arr[1];
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = imLogMapper.queryUserMsgCountByKeyword(p, beginDate, endDate);

        data.put("datas", iPage.getRecords());
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查看查杀消息记录列表数据");

        return Result.returnSuccess(data);
    }
}
